package com.financing.platform.web;

import java.io.File;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.financing.platform.dto.CorpProjectDTO;
import com.financing.platform.dto.ProductAttachmentDTO;
import com.financing.platform.dto.ProductRecommendDTO;
import com.financing.platform.dto.ProjectAccountDTO;
import com.financing.platform.dto.ProjectAnnualRevenueDTO;
import com.financing.platform.dto.ProjectDTO;
import com.financing.platform.dto.ProjectRabateDTO;
import com.financing.platform.dto.ProjectRiskDTO;
import com.financing.platform.service.ICompanyService;
import com.financing.platform.service.IProductRecommendService;
import com.financing.platform.service.IProjectAccountService;
import com.financing.platform.service.IProjectAnnualRevenueService;
import com.financing.platform.service.IProjectCommentsService;
import com.financing.platform.service.IProjectRabateService;
import com.financing.platform.service.IProjectRiskService;
import com.financing.platform.service.IProjectService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.Dict;
import com.financing.platform.util.FileUtil;
import com.financing.platform.util.StringUtil;

@Controller
public class ProjectUpdateAction extends BaseAction{
	
	@Autowired
	private IProjectService projectServiceImpl;
	
	@Autowired
	private IProjectAnnualRevenueService projectAnnualRevenueServiceImpl; 
	
	@Autowired
	private IProjectRabateService projectRabateSericeImpl;
	
	@Autowired
	private IProjectCommentsService projectCommentsServiceImpl;
	
	@Autowired
	private IProjectRiskService projectRiskServiceImpl;
	
	@Autowired
	private IProductRecommendService productRecommendServiceImpl;
	
	@Autowired
	private ICompanyService companyServiceImpl;
	
	@Autowired
	private IProjectAccountService projectAccountServiceImpl;
	
	@Value("#{settings['fileBaseDir']}")
	private String fileBaseDir;
	
	@Value("#{settings['productFileDir']}")
	private String fileDir;
	
	@RequestMapping("/updateProjectPer.shtml")
	public ModelAndView updateProjectPer(HttpServletRequest request,
			HttpServletResponse response) {
			request.getSession().setAttribute(Dict.requestID, "updateProjectPer.shtml");
			return new ModelAndView("updateProjectPer");
	}
	
	/**
	 * 
	* @Title: queryUpdateProjectList 
	* @Description: 产品列表
	* @param   request
	* @param   response
	* @param   projectDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/queryUpdateProjectList.shtml")
	public ModelAndView queryUpdateProjectList(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		List<ProjectDTO> projectList =  projectServiceImpl.queryAllProject(projectDTO);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("projectList", projectList);
		resultMap.put("projectDTO", projectDTO);
		return new ModelAndView("updateProjectList",resultMap);
	}
	
	/**
	 * 
	* @Title: queryUpdateProject 
	* @Description: 产品详情
	* @param   request
	* @param   response
	* @param     projectDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/queryUpdateProject.shtml")
public ModelAndView queryUpdateProject(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		ProjectDTO project =  projectServiceImpl.queryProject(projectDTO);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("project", project);
		return new ModelAndView("updateProjectDetail",resultMap);
	}
	
	@RequestMapping("/updateProjectBaseInfo.shtml")
	public ModelAndView updateProjectBaseInfo(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());
			projectDTO.setpExpectSubscriptionAmount(projectDTO.getpIssuingScale());
			if(projectDTO.getpIssuingScale() != null){
				projectDTO.setpIssuingScale(projectDTO.getpIssuingScale().multiply(new BigDecimal(100000000)));
			}
			if(projectDTO.getpExpectSubscriptionAmount() != null){
				projectDTO.setpExpectSubscriptionShare(projectDTO.getpExpectSubscriptionAmount().multiply(new BigDecimal(100000000)));
			}
			if(projectDTO.getpMinimumAmount() != null){
				projectDTO.setpMinimumAmount(projectDTO.getpMinimumAmount().multiply(new BigDecimal(10000)));
			}
			if(projectDTO.getpExpectSubscriptionAmount() != null){
				projectDTO.setpExpectSubscriptionAmount(projectDTO.getpExpectSubscriptionAmount().multiply(new BigDecimal(100000000)));
			}
			if(projectDTO.getpProgressiveAmount() != null){
				projectDTO.setpProgressiveAmount(projectDTO.getpProgressiveAmount().multiply(new BigDecimal(10000)));
			}
			//projectDTO.setStatus(Dict.pProductStatus_need_Verify);
			//projectDTO.setpPublicStatus(Dict.pPublicStatus_No_public);
			
			try {
				uploadProductFiles(request,projectDTO);
			} catch (Exception e) {
				log.error("save file error!",e);
				resultMap.put(Dict.result, Dict.result_error);
				return new ModelAndView("updateProjectPer",resultMap);
			}
			
			resultMap.put(Dict.result, projectServiceImpl.updateProject(projectDTO,null));
		} catch (SQLException e) {
			log.error("update project error!",e);
			resultMap.put(Dict.result, Dict.result_error);
		}
		return new ModelAndView("updateProjectPer",resultMap);
	}
	
	/**
	 * 
	* @Title: uploadProductFiles 
	* @Description: 保存附件
	* @param   request
	* @return List<ProductAttachmentDTO>   
	* @throws
	 */
	private  List<ProductAttachmentDTO> uploadProductFiles(HttpServletRequest request,ProjectDTO projectDTO) throws Exception{
		
		List<ProductAttachmentDTO> productAttachmentDTOList = new ArrayList<ProductAttachmentDTO>() ;
		
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
           //获取multiRequest 中所有的文件名
            Map<String,MultipartFile> mutipartFileMap = multiRequest.getFileMap();
             
            Iterator<Entry<String, MultipartFile>> mutipartFileIterator =  mutipartFileMap.entrySet().iterator();
            while(mutipartFileIterator.hasNext())
            {
            	Entry<String, MultipartFile> entry = mutipartFileIterator.next();
                MultipartFile file=entry.getValue();
                if(file!=null && (!file.isEmpty()) &&  (!StringUtil.isNullOrEmptyStr(entry.getKey())))
                {
                	StringBuffer fileFullPath = new StringBuffer();
                	fileFullPath.append(fileBaseDir)
                				.append(fileDir)
                				.append("/")
                				.append(StringUtil.dateNowStr("yyyyMMdd"))
                				.append("/")
                				.append(System.currentTimeMillis())
								.append(file.getOriginalFilename());
                	File dir = new File(fileFullPath.toString());
                	if(!dir.exists()){
                		dir.mkdirs();
                	}
                	
                	//上传
                    FileUtil.saveFile(file, fileFullPath.toString());
                    
                	if("image".equals(entry.getKey())){
                		projectDTO.setpImageUri(fileFullPath.toString().substring(fileBaseDir.length()));
                	}else{
	                    ProductAttachmentDTO productAttachmentDTO = new ProductAttachmentDTO();
	                    productAttachmentDTO.setfName(file.getOriginalFilename());
	                    productAttachmentDTO.setfUploadTime(new Date());
	                    productAttachmentDTO.setfType(file.getContentType());
	                    productAttachmentDTO.setfPath(fileFullPath.toString().substring(fileBaseDir.length()));
	                    productAttachmentDTOList.add(productAttachmentDTO);
                	}
                }
                 
            }
           
        }
		
		return productAttachmentDTOList;
		
	}
	
	@RequestMapping("/queryUpdateProjectAccount.shtml")
	public ModelAndView queryUpdateProjectAccount(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		List<ProjectAccountDTO> projectAccount =  projectAccountServiceImpl.queryProjectAccountList(projectDTO.getId());
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("projectAccount", projectAccount);
		resultMap.put("project", projectDTO);
		return new ModelAndView("updateProjectAccountDetail",resultMap);
	}
	
	@RequestMapping("/updateProjectAccount.shtml")
	public ModelAndView updateProjectAccount(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		String[] pProjectId = request.getParameterValues("pProjectId");
		String[] pRaiseAccountName = request.getParameterValues("pRaiseAccountName");
		String[] pRaiseAccountNo = request.getParameterValues("pRaiseAccountNo");
		String[] pRaiseAccountOpenAddr =request.getParameterValues("pRaiseAccountOpenAddr");

		ProjectAccountDTO projectAccountDTO = new ProjectAccountDTO();
		DTOdateSet.setCreateInfo(projectAccountDTO, request.getSession());
		DTOdateSet.setUpdateInfo(projectAccountDTO, request.getSession());
		
		ProjectDTO projectTmp = new ProjectDTO();
		projectTmp.setId(projectDTO.getId());
		projectTmp.setStatus(Dict.pProductStatus_need_Verify);
		projectTmp.setpPublicStatus(Dict.pPublicStatus_No_public);
		DTOdateSet.setUpdateInfo(projectTmp, request.getSession());
		try {
			projectServiceImpl.updateProject(projectDTO,null);
			projectAccountServiceImpl.deleteProjectAccount(projectDTO.getId());
		} catch (SQLException e1) {
			log.error("add project account error " ,e1);
			resultMap.put(Dict.result, Dict.result_error);
			return new ModelAndView("updateProjectPer",resultMap);
		}
		for(int i = 0 ;i < pProjectId.length ; i++){
			if(!StringUtil.isNullOrEmptyStr(pRaiseAccountNo[i])){
				projectAccountDTO.setpProjectId(pProjectId[i]);
				projectAccountDTO.setpRaiseAccountName(pRaiseAccountName[i]);
				projectAccountDTO.setpRaiseAccountNo(pRaiseAccountNo[i]);
				projectAccountDTO.setpRaiseAccountOpenAddr(pRaiseAccountOpenAddr[i]);
				try {
					projectAccountServiceImpl.addProjectAccount(projectAccountDTO);
				} catch (SQLException e) {
					log.error("add project account error " ,e);
					resultMap.put(Dict.result, Dict.result_error);
				}
			}
		}
		
		resultMap.put(Dict.result, Dict.result_success);
		
		return new ModelAndView("updateProjectPer",resultMap);
	}
	
	@RequestMapping("/queryUpdateProjectAnnualRevenue.shtml")
	public ModelAndView queryUpdateProjectAnnualRevenue(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		List<ProjectAnnualRevenueDTO> projectAccount =  projectAnnualRevenueServiceImpl.queryProjectAnnualRevenue(projectDTO.getId());
		ProjectRabateDTO projectRabateDTO = new ProjectRabateDTO();
		projectRabateDTO.setpId(projectDTO.getId());
		List<ProjectRabateDTO> projectRabateList  = projectRabateSericeImpl.queryProjectRabate(projectRabateDTO);
		CorpProjectDTO corpProjectDTO = new CorpProjectDTO();
		try {
			corpProjectDTO = projectServiceImpl.queryCorpProject(projectDTO.getId());
		} catch (SQLException e) {
			log.error("query project corp error!",e);
		}
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("projectAnnualRevenue", projectAccount);
		resultMap.put("project", projectDTO);
		resultMap.put("projectRabateList", projectRabateList);
		resultMap.put("corpProjectDTO", corpProjectDTO);
		return new ModelAndView("updateProjectAnnualRevenueDetail",resultMap);
	}
	
	@RequestMapping("/updateProjectAnnualRevenue.shtml")
	public ModelAndView updateProjectAnnualRevenue(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String[] projectId = request.getParameterValues("pId");
		String[] pAnnualRevenueExpect = request.getParameterValues("pAnnualRevenueExpect");
		String[] pStartAmount = request.getParameterValues("pStartAmount");
		String[] pEndAmount =request.getParameterValues("pEndAmount");
		String[] pRabateType = request.getParameterValues("pRabateType");
		String[] pRabateProfit = request.getParameterValues("pRabateProfit");
		
		ProjectDTO project = new ProjectDTO();
		ProjectDTO projectTmp = new ProjectDTO();
		projectTmp.setId(projectDTO.getId());
		projectTmp.setStatus(Dict.pProductStatus_need_Verify);
		projectTmp.setpPublicStatus(Dict.pPublicStatus_No_public);
		DTOdateSet.setUpdateInfo(projectTmp, request.getSession());
		
		try {
			projectServiceImpl.updateProject(projectDTO,null);
			projectAnnualRevenueServiceImpl.deleteProjectAnnualRevenue(projectDTO.getId());
			projectRabateSericeImpl.deleteProjectRabate(projectDTO.getId());
		} catch (SQLException e) {
			resultMap.put(Dict.result, Dict.result_error);
			resultMap.put("project", projectDTO);
			return new ModelAndView("updateProjectPer",resultMap);
		}
		
		for(int i = 0;i<projectId.length; i++){
			
			project.setId(Integer.valueOf(projectId[i]));
			
			project = projectServiceImpl.queryProject(project);
			if(project.getId() == null){
				continue;
			}
			
			ProjectAnnualRevenueDTO projectAnnualRevenueDTO = new ProjectAnnualRevenueDTO();
			ProjectRabateDTO projectRabateDTO = new ProjectRabateDTO();
			
			projectAnnualRevenueDTO.setpAnnualRevenueExpect(pAnnualRevenueExpect[i]);
			projectAnnualRevenueDTO.setpStartAmount(new BigDecimal(pStartAmount[i]).multiply(new BigDecimal(10000)));
			projectAnnualRevenueDTO.setpEndAmount(new BigDecimal(pEndAmount[i]).multiply(new BigDecimal(10000)));
			projectAnnualRevenueDTO.setpId(Integer.valueOf(projectId[i]));
			if(pRabateType != null && pRabateType.length > 0){
				projectRabateDTO.setpRabateProfit(new BigDecimal(pRabateProfit[i]));
				projectRabateDTO.setpRabateType(pRabateType[i]);
				projectRabateDTO.setpId(Integer.valueOf(projectId[i]));
				DTOdateSet.setCreateInfo(projectRabateDTO, request.getSession());
				DTOdateSet.setUpdateInfo(projectRabateDTO, request.getSession());
			}
			
			DTOdateSet.setCreateInfo(projectAnnualRevenueDTO, request.getSession());
			DTOdateSet.setUpdateInfo(projectAnnualRevenueDTO, request.getSession());
			
			int arId = projectAnnualRevenueServiceImpl.insertProjectAnnualRevenue(projectAnnualRevenueDTO);
			//arId 为-1 则年化益率插入失败
			if(arId == -1){
				resultMap.put(Dict.result, Dict.result_error);
				break;
			}
			if(pRabateType != null && pRabateType.length > 0){
				projectRabateDTO.setArId(arId);
				projectRabateSericeImpl.addProjectRabateInfo(projectRabateDTO);
			}
			resultMap.put(Dict.result, Dict.result_success);
		}
		return new ModelAndView("updateProjectPer",resultMap);
	}
	
	@RequestMapping("/deleteProject.shtml")
	@ResponseBody
	public Map<?,?> deleteProject(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put(Dict.result, Dict.result_error);
		projectDTO.setpPublicStatus(Dict.pPublicStatus_No_public);
		projectDTO = projectServiceImpl.queryProject(projectDTO);
		if(projectDTO != null && projectDTO.getId() != null ){
			try{
				projectAccountServiceImpl.deleteProjectAccount(projectDTO.getId());
				projectAnnualRevenueServiceImpl.deleteProjectAnnualRevenue(projectDTO.getId());
				projectRabateSericeImpl.deleteProjectRabate(projectDTO.getId());
				projectServiceImpl.deleteProject(projectDTO.getId());
				ProductRecommendDTO productRecommendDto = new ProductRecommendDTO();
				productRecommendDto.setFpProjectId(projectDTO.getId());
				productRecommendServiceImpl.deleteProductRecommend(productRecommendDto);
				projectRiskServiceImpl.deleteProjectRisk(projectDTO.getId());
				resultMap.put(Dict.result, Dict.result_success);
			}catch(Exception e){
				log.error("delete project info error ",e);
			}
		}
		
		return resultMap;
	}
	
	@RequestMapping("/changepRecruitmentSummary.shtml")
	@ResponseBody
	public Map<?,?> changepRecruitmentSummary(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		ProjectDTO projectTmp = new ProjectDTO();
		projectTmp.setId(projectDTO.getId());
		projectTmp.setpRecruitmentSummary(projectDTO.getpRecruitmentSummary());
		projectTmp.setStatus(Dict.pProductStatus_need_Verify);
		projectTmp.setpPublicStatus(Dict.pPublicStatus_No_public);
		try {
			resultMap.put(Dict.result, projectServiceImpl.updateProject(projectDTO,null));
		} catch (SQLException e) {
			resultMap.put(Dict.result, Dict.result_error);
			log.error("changepRecruitmentSummary error :",e);
		}
		return resultMap;
	}
	@RequestMapping("/queryUpdateProjectRisk.shtml")
	public ModelAndView queryUpdateProjectRisk(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		ProjectRiskDTO projectRiskDto = new ProjectRiskDTO();
		projectRiskDto.setpId(projectDTO.getId());
		List<ProjectRiskDTO> projectRiskList = projectRiskServiceImpl.queryProjectRisk(projectRiskDto);
		if(projectRiskList.size()>0){
			projectRiskDto = projectRiskList.get(0);
		}
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		resultMap.put("projectRisk", projectRiskDto);
		return new ModelAndView("updateProjectRisk",resultMap);
	}
	@RequestMapping("/updateProjectRisk.shtml")
	@Transactional
	public ModelAndView updateProjectRisk(HttpServletRequest request,
			HttpServletResponse response,ProjectRiskDTO projectRiskDto) {
		
		Map<String,Object> result = new HashMap<String,Object>();
		DTOdateSet.setCreateInfo(projectRiskDto, request.getSession());
		try {
			projectRiskServiceImpl.deleteProjectRisk(projectRiskDto.getpId());
			result.put(Dict.result, projectRiskServiceImpl.addProjectRisk(projectRiskDto));
		} catch (SQLException e) {
			log.error("update project error!",e);
			result.put(Dict.result, Dict.result_error);
		}
		return new ModelAndView("updateProjectPer",result);
	}
}
